package Server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {
	
	private Socket socket;
	
	private InputStream inFlow;
	
	private String path = "//Users/liucz/works/projects/J2EE/ContainerL";
	
	private PrintStream out;
	
	public Processor(Socket socket) {
		this.socket = socket;
		try {
			inFlow = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		String file = parseContent(inFlow);
		forwardContent(file);
	}
	
	private String parseContent(InputStream in){
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String file = null;
		try {
			String httpMessage = br.readLine();
			System.out.println("httpMessage : " + httpMessage);
			String[] messages = httpMessage.split(" ");
			file = messages[1];
			System.out.println(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}
	
	private void forwardContent(String file){
		File contentFile = new File(path+file);
		if(!contentFile.exists()){
			System.out.println("show error");
		}else{
			try {
				InputStream ins = new FileInputStream(contentFile);
				byte[] content = new byte[(int)contentFile.length()];
				ins.read(content);
//				out.println("HTTP/1.0	200 loginfile");
//				out.println("Content-length:" + content.length);
//				out.println();
				out.write(content);
				out.flush();
				ins.close();
				out.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}


	
	
}
